package cfca.paperless.client.servlet._2_extend._2_02_CompoundAutoCalculatePdfHash;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

import cfca.paperless.client.bean.MultiDataBean;
import cfca.paperless.client.bean.SealUserInfo;
import cfca.paperless.client.bean.SignLocation;
import cfca.paperless.client.servlet.PaperlessClient;
import cfca.paperless.client.servlet.PaperlessConfig;
import cfca.paperless.client.util.GUID;
import cfca.paperless.client.util.IoUtil;
import cfca.paperless.client.util.PaperlessUtil;
import cfca.paperless.client.util.StrategyUtil;
import cfca.paperless.client.util.StringUtil;
import cfca.sadk.util.Base64;

public class CompoundAutoCalculatePdfHashTest01 {

    /**
     * 复合计算pdf hash
     * @param args
     */
    public static void main(String[] args) {
        try {
            long timeStart = System.currentTimeMillis();// 开始时间

            PaperlessClient clientBean = new PaperlessClient(PaperlessConfig.extUrl, 10000, 60000);// 无纸化辅助接口的访问URL

            
            String filePath = "./TestData/autoCalculatePdfHash.pdf";
            byte[] pdf = FileUtils.readFileToByteArray(new File(filePath));
            byte[] x509Cert = FileUtils.readFileToByteArray(new File("./TestData/cert/tl1024.cer"));
            
            byte[] handwritingImage = FileUtils.readFileToByteArray(new File("./TestData/zhangfei.png"));
            byte[] handwritingData = handwritingImage;
            byte[] identificationFrontData = FileUtils.readFileToByteArray(new File("./TestData/1.png"));
            byte[] identificationBackData =FileUtils.readFileToByteArray(new File("./TestData/2.png"));
            List<MultiDataBean> list1 = new ArrayList<MultiDataBean>();
            list1.add(new MultiDataBean(handwritingData, "handwritingData.dat", "media-id", "2"));//手写签名数据
            list1.add(new MultiDataBean(handwritingImage, "handwritingImage.png", "2"));//手写签名图片
            list1.add(new MultiDataBean(identificationFrontData, "identificationFrontImage.png", "2"));//身份证正面
            list1.add(new MultiDataBean(identificationBackData, "identificationBackImage.png", "2"));//身份证反面
            String proofHashAndMultiData1[] = PaperlessUtil.getProofHashAndMultiData(list1);
            
            String proofHashXml = proofHashAndMultiData1[0];
            String multiData = "[" + proofHashAndMultiData1[1] + "]";
            
            SealUserInfo sealUserInfo = new SealUserInfo("张三三", "Z", "0003aa222157", "15744659823", "北京", "签合同");
            String userInfoXml = PaperlessUtil.buildUserInfo(sealUserInfo);
            // 操作员编码或者机构号
            String operatorCode = PaperlessConfig.operatorCode;
            // 渠道编码，可以为空
            String channelCode = PaperlessConfig.channelCode;
            
            SignLocation signLocation = new SignLocation("代理人签名", "R", 10, 10);
            // get pdf hash
            String proofSealStrategyXml = StrategyUtil.createProofSealStrategyXml(handwritingImage, sealUserInfo, signLocation, proofHashXml);
            
            // 获取时间戳的方式。默认值为0。0：实时访问CFCA 时间戳服务；1：使用从CFCA购置并在本地部署的时间戳服务器产品；
            String timestampChannel = "0";
            
            
            String returnMessage = clientBean.compoundAutoCalculatePdfHash(pdf, null, multiData, proofSealStrategyXml, operatorCode, channelCode, timestampChannel);
            String code = StringUtil.getNodeText(returnMessage, "Code");
            if ("200".equals(code)) {
                System.out.println("OK:autoCalculatePdfHash");
                String pdfSealHash = StringUtil.getNodeText(returnMessage, "PdfSealHash");
                String pdfSealSource = StringUtil.getNodeText(returnMessage, "PdfSealSource");
                String authCodeXml = "<AuthCode><AuthCodeValue>793959</AuthCodeValue><AuthCodeId>201608121815042141297487563305</AuthCodeId></AuthCode>";
                String id = StringUtil.getNodeText(returnMessage, "Id");
                //对pdf hash签名，可以采用场景证书签名也可以采用固定证书签名
//                String signMessage = clientBean.signAutoPdfProofHash(pdfHashListXml, userInfoXml, proofHashXml, "", operatorCode, channelCode);//场景证书签名
                String pdfHashSignListXml = "<List><PdfHashSign>" +
                                            "<PdfSealHash></PdfSealHash>" +
                                            "<PdfSealSource>" + pdfSealSource + "</PdfSealSource>" +
                                            "<BizTypeCode></BizTypeCode>" +
                                            "<SealCode>yz2018052435698224</SealCode>" +
                                            "<SealPassword>cfca1234</SealPassword>" +
                                            "</PdfHashSign></List>";
                String signMessage = clientBean.signAutoPdfHash(pdfHashSignListXml, "", operatorCode, channelCode);//固定证书签名
                code = StringUtil.getNodeText(signMessage, "Code");
                if ("200".equals(code)) {
                    System.out.println("OK:autoCalculatePdfHash");
                    String pkcs7 = StringUtil.getNodeText(signMessage, "Pkcs7");
                    System.out.println("返回的pkcs7：" + pkcs7);
                    String systemNo = GUID.generateId();//业务流水号 
                    byte[] sealedPdfData = clientBean.synthesizeOuterSignature(systemNo,Base64.decode(pkcs7), id, operatorCode, channelCode);
                    String errorRsString = PaperlessUtil.isError(sealedPdfData);

                    if ("".equals(errorRsString)) {
                        System.out.println("OK:synthesizeOuterSignature");
                        String rs = "./TestData/output/compoundAutoCalculatePdfHash-" + new File(filePath).getName() + ".pdf"; 
                        System.out.println(sealedPdfData.length);
                        System.out.println(rs);
                        IoUtil.write(rs, sealedPdfData);
                    } else {
                        // 处理结果为异常，打印出错误码和错误信息
                        System.out.println("NG:synthesizeOuterSignature");
                        System.out.println(sealedPdfData.length);
                        System.out.println(new String(sealedPdfData, "UTF-8"));
                    }
                    
                } else {
                    System.out.println(signMessage);
                }
                long timeEnd = System.currentTimeMillis();// 结束时间
                System.out.println("time:" + (timeEnd - timeStart));
            } else {
                System.out.println(returnMessage);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
